package org.shreker.tools.utils.cookie;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginCookieUtil {

    private final static String COOKIE_DOMAIN = ".shreker.com";
    private final static String COOKIE_NAME = "login_token";

    public static String getLoginToken(HttpServletRequest request) {
        Cookie[] cks = request.getCookies();
        if (cks != null && cks.length > 0) {
            for (Cookie ck : cks) {
                if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
                    return ck.getValue();
                }
            }
        }
        return null;
    }

    public static void setLoginToken(HttpServletResponse response, String token) {
        Cookie ck = new Cookie(COOKIE_NAME, token);
        ck.setDomain(COOKIE_DOMAIN);
        ck.setPath("/");//代表设置在根目录
        ck.setHttpOnly(true);// 设置无法使用脚本访问Cookie
        //如果这个maxage不设置的话，cookie就不会写入硬盘，而是写在内存。只在当前页面有效。单位是秒
        ck.setMaxAge(60 * 60 * 24 * 365);//如果是-1，代表永久
        response.addCookie(ck);
    }

    public static void deleteLoginToken(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cks = request.getCookies();
        if (cks != null && cks.length > 0) {
            for (Cookie ck : cks) {
                if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
                    ck.setDomain(COOKIE_DOMAIN);
                    ck.setPath("/");
                    ck.setMaxAge(0);//设置成0，代表删除此cookie。
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }

}
